package com.ruyuan.starter.async.thread;

import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 创建业务线程池的都可以从这里获取一个自定义线程名的线程工厂
 *
 * @author zhonghuashishan
 */
public class NamedDaemonThreadFactory implements ThreadFactory {

    private static final ConcurrentHashMap<String, NamedDaemonThreadFactory> BUFFER = new ConcurrentHashMap<>();

    private final String name;

    private final AtomicInteger counter = new AtomicInteger(0);

    private NamedDaemonThreadFactory(String name) {
        this.name = name;
    }

    public static NamedDaemonThreadFactory getInstance(String name) {
        Objects.requireNonNull(name, "必须要传一个线程名字的前缀");
        return BUFFER.computeIfAbsent(name, NamedDaemonThreadFactory::new);
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r, name + "-" + counter.incrementAndGet());
        thread.setDaemon(true);
        return thread;
    }
}